﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.MediaPlayer.Interop;
using System.Diagnostics;

namespace BMproductions.Media.MediaPlayer.WMPPlus {
	public abstract class WMPPlug: ContextBoundObject, IDisposable, IWMPPluginUI {
		public int WMPlayerVersion {
			get { return WMPPlusCore.GetIntProp(WMPPlusProperty.WMPVersion); }
			set { WMPPlusCore.SetIntProp(WMPPlusProperty.WMPVersion, value); }
		}
		protected IWMPCore core = null;
		
		public IWMPCore WMPCore { get { return this.core; } }

		public WMPPlug() {
			//try {
			//    MUIResourceManager.LoadMUIResourceManager(typeof(Resources), Resources.Culture, Resources.ResourceManager);
			//} catch (Exception ex) {
			//    Trace.WriteLine("Exception on load mui: " + ex.Message);
			//}
		}

		void IDisposable.Dispose() {
			ClearCore();
		}

		protected virtual void Init() { }

		public virtual void Dispose() { }

		void ClearCore() {
			if (this.core != null)
				Dispose();
			this.core = null;
		}

		#region IWMPPluginUI implementation
		public virtual HResult Create(IntPtr hwndParent, out IntPtr hwndWindow) {
			hwndWindow = IntPtr.Zero;
			return HResult.S_OK;
		}

		public virtual HResult Destroy() {
			return HResult.S_OK;
		}

		public virtual HResult DisplayPropertyPage(IntPtr hwndParent) {
			return HResult.S_OK;
		}

		public virtual HResult GetProperty(string wszName, out object varProperty) {
			varProperty = null;
			try {
				if (wszName != WMPConstants.PLUGIN_MISC_QUERYDESTROY)
					return HResult.E_NOTIMPL;
				varProperty = String.Empty;
				return HResult.S_OK;
			} catch {
				return HResult.E_FAIL;
			}
		}

		public virtual HResult SetCore(object Core) {
			ClearCore();
			try {
				this.core = Core as IWMPCore;
				if (this.core != null) {
					if (this.WMPlayerVersion == 0)
						this.WMPlayerVersion = WMPUtils.GetMajorVersion(this.core.versionInfo);
					Init();
				}
				return HResult.S_OK;
			} catch (Exception ex) {
				Trace.WriteLine(ex.Message);
				Debug.WriteLine(ex.ToString());
				return HResult.E_FAIL;
			}
		}

		public virtual HResult SetProperty(string pwszName, ref object varProperty) {
			return HResult.E_NOTIMPL;
		}

		public virtual HResult TranslateAccelerator(IntPtr lpmsg) {
			return HResult.E_FAIL;
		}
		#endregion
	}
}
